package com.ciei.dpagm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;

public class MD5Util {

	/**
	 * 文件MD5加密
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 */
	public static byte[] getFileMD5(File file) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");  
        
        FileInputStream fis = new FileInputStream(file);  

        byte[] buffer = new byte[2048];  

        int length = -1;  

        while ((length = fis.read(buffer)) != -1) {  

            md.update(buffer, 0, length);  

        }  

        byte[] b = md.digest();  
        
        fis.close();
        return b;
	}
	
	public static int getUnixTimeStamp(){
        long rest=System.currentTimeMillis()/1000L;
        return (int)rest;
    }

    /**
     * 将传入的值使用md5加密之后返回加密后的字符串
     * @param value
     * @author pp
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String getStringMD5(String value) throws NoSuchAlgorithmException, UnsupportedEncodingException{
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(value.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
